import React, { Component } from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { Split, TitleLine, TextLine, TextCell } from '@components/ApprovePre/Approve'
import { defaultProcedure } from '@src/assets/js/config'

export default class SecretaryGeneralHistory extends Component {
  state = {
    varsMap: {}
  }

  // 初始化vars映射对象
  initVarsMap () {
    const varsMap = {}
    const vars = (this.props.action || {}).vars || []
    vars.forEach(li => {
      varsMap[li.key] = li.value
    })
    this.setState({ varsMap })
  }

  // 格式化日期
  formatDate (date) {
    if (date) {
      return moment(date * 1000).format('YYYY-MM-DD HH:mm')
    }
  }

  componentDidUpdate (prev) {
    if (prev.action !== this.props.action) {
      this.initVarsMap()
    }
  }

  componentDidMount () {
    this.initVarsMap()
  }

  // 渲染仲裁员详情链接
  renderArbitratorLink (name, id) {
    if (typeof id === 'string' && id.length > 0) {
      return <a onClick={() => this.props.showArbitratorDetail(id)}>{name}</a>
    }
    return name
  }

  renderNormal () {
    const { caseDetail } = this.props
    if (caseDetail.procedure === defaultProcedure) {
      const varsMap = this.state.varsMap
      return (
        <>
          <Split />
          <TextCell>仲裁员：{this.renderArbitratorLink(varsMap.arbitrator1, varsMap.arbitratorid1) || '无'}</TextCell>
          <Split />
          <TextCell>仲裁员：{this.renderArbitratorLink(varsMap.arbitrator2, varsMap.arbitratorid2) || '无'}</TextCell>
        </>
      )
    }
  }

  render () {
    const { action } = this.props
    const varsMap = this.state.varsMap
    const isNormal = this.props.caseDetail.procedure === defaultProcedure
    return (
      <div>
        <TitleLine title={this.props.action.step_name} operator={action.operator} time={this.formatDate(action.complete_datetime)} />
        <TextLine>
          <TextCell>操作：{action.action_name}</TextCell>
          <Split />
          <TextCell style={{ width: '65%' }}>备注：{action.remark || '无'}</TextCell>
        </TextLine>
        <TextLine>
          <TextCell>{isNormal ? '首席仲裁员' : '仲裁员'}：{this.renderArbitratorLink(varsMap.arbitrator, varsMap.arbitratorid) || '无'}</TextCell>
          {this.renderNormal()}
        </TextLine>
        {this.props.renderDocument()}
      </div>
    )
  }
}

SecretaryGeneralHistory.proptypes = {
  userInfo: PropTypes.object,
  instance: PropTypes.object,
  action: PropTypes.object,
  caseDetail: PropTypes.object,
  renderDocument: PropTypes.func,
  showArbitratorDetail: PropTypes.func
}

SecretaryGeneralHistory.defaultProps = {
  userInfo: {},
  instance: {},
  action: {},
  caseDetail: {},
  renderDocument: () => {},
  showArbitratorDetail: () => {}
}
